unit BubbleSortFlag;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, ExtCtrls;

const
  N = 50;
  w = 10;
  h = 10;
  x0 = 0;
  y0 = 0;
type
  TForm1 = class(TForm)
    Timer1: TTimer;
    Button1: TButton;
    Image1: TImage;
    ScrollBar1: TScrollBar;
    procedure Button1Click(Sender: TObject);
    procedure Timer1Timer(Sender: TObject);
    procedure ScrollBar1Change(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;
  arr: array of integer;
  i, j, a, k, runNumber, step, flag, t: integer;
implementation

{$R *.dfm}

procedure Draw;
begin
  Form1.Image1.Canvas.Rectangle(0, 0, Form1.Image1.Width, Form1.Image1.Height);
  for k:=0 to N-1 do
  begin
    if (k=step) or (k=step+1) then
      Form1.Image1.Canvas.Brush.Color:=clRed
    else
      Form1.Image1.Canvas.Brush.Color:=clWhite;
    Form1.Image1.Canvas.Rectangle(x0 + w*k, y0, x0+w*(k+1), y0+h*arr[k]);
  end;
  Form1.Image1.Canvas.Brush.Color:=clWhite;
end;

procedure TForm1.Timer1Timer(Sender: TObject);
begin
  if (runNumber<=N-2) and (t=1) then
  begin
    if (step<=N-2-runNumber) then
    begin
      if (arr[step]>arr[step+1]) then
      begin
        a:=arr[step+1];
        arr[step+1]:=arr[step];
        arr[step]:=a;
        Draw;
        Image1.Refresh;
        step:=step+1;
        flag:=0;
      end
      else
      begin
        Draw;
        step:=step+1;
      end;
    end
    else
    begin
      if (flag=0) then
        t:=1
      else
        t:=0;
      runNumber:=runNumber+1;
      flag:=1;
      Image1.Refresh;
      step:=0;
    end;
  end
  else
  begin
    Timer1.Enabled:=False;
    ShowMessage('Array has been sorted');
  end;
end;


procedure TForm1.Button1Click(Sender: TObject);
begin
  t:=1;
  runNumber:=0;
  step:=0;
  setlength(arr, N);
  randomize;
  for i:=0 to N-1 do
    arr[i]:=random(N);
  Draw;
  Timer1.Enabled:=True;
end;


procedure TForm1.ScrollBar1Change(Sender: TObject);
begin
  Timer1.Interval:=(ScrollBar1.Max+1)-(ScrollBar1.Position);
end;

end.
